function trafficLights(road, n) {
    var lights = [...road].map((v, i) => new Object({ 'clr': v, 'idx': i, 'secs': 0 })).filter(v => /[RGO]/.test(v.clr));
    var cars = [...road].map((v, i) => [v, i]).filter(v => v[0] === 'C').map(v => v[1]).sort((a, b) => b - a);
    var roads = [...road].map(v => '.');
    function switchLight() {
        for (light of lights) {
            light.secs++;
            if (light.clr === 'G' && light.secs === 5) { light.clr = 'O'; light.secs = 0; }
            else if (light.clr === 'O' && light.secs === 1) { light.clr = 'R'; light.secs = 0; }
            else if (light.clr === 'R' && light.secs === 5) { light.clr = 'G'; light.secs = 0; }
            roads[light.idx] = light.clr;
        }
    }

    var out = [road];
    for (var i = 1; i <= n; i++) {
        switchLight();
        for (var j = 0; j < cars.length; j++) {
            var p = cars[j];
            if (p + 1 >= road.length) {
                //drive to the end of the road
                if (temp = lights.find(v => v.idx === p)) {
                    roads[p] = temp.clr;
                } else roads[p] = '.';
                roads[++cars[j]] = '.';
            } else {
                if (roads[p + 1] === '.') {
                    if (temp = lights.find(v => v.idx === p)) {
                        roads[p] = temp.clr;
                    } else roads[p] = '.';
                    roads[++cars[j]] = 'C';
                } else if (roads[p + 1] === 'G') {
                    if (roads[p + 2] != 'C') {
                        if (temp = lights.find(v => v.idx === p)) {
                            roads[p] = temp.clr;
                        } else roads[p] = '.';
                        roads[++cars[j]] = 'C';
                    }
                } else {
                    roads[p] = 'C';
                }
            }
        }
        out.push(roads.join('').slice(0, road.length))
    }
    return out;
}

